<template>
    <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"        
        
        @row-del="handleDel"
        @refresh-change="handleRefreshChange"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @row-update="handleUpdate"
        @search-change="handleSearchChange"
      >
      <template slot="menuLeft" v-if="!isSelect">
        
        <el-button
        type="primary"
        @click="handleExport"
        :loading="downloadLoading"
        icon="el-icon-download"
        v-perm="'/admin/video-channel/export'"
        size="small"
      >导出</el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <div>
             <!-- <el-button
            type="text"
            @click.stop="handleSelectDataItem(scope.row)"
            v-if="isSelect"
            icon="el-icon-edit"
            size="mini"
            >选择</el-button> -->
            <el-button
            type="text"
            @click.stop="handleSetTopFlag(scope.row,1)"
            v-if="scope.row.topFlag==0"
            icon="el-icon-edit"
            size="mini"
            >置顶</el-button>
              <el-button
            type="text"
            @click.stop="handleSetTopFlag(scope.row,0)"
            v-if="scope.row.topFlag==1"
            icon="el-icon-edit"
            size="mini"
            >取消置顶</el-button>
            <el-button
            type="text"
            @click.stop="hanldePlay(scope.row)"
            v-if="scope.row.recordVideoUrl"
            icon="el-icon-edit"
            size="mini"
            >播放录播</el-button>
             <el-button
            type="text"
            @click.stop="handleShowSetPlayView(scope.row)"
            icon="el-icon-edit"
            size="mini"
            >设置虚拟播放次数</el-button>
          </div>
      </template>
      </avue-crud>
      </basic-container>
      <el-dialog :visible.sync="videoPriviewDialogShowed" title="视频播放" width="500px" @closed="handleCloseDialog">
          <video ref="myVideo" class="video-js vjs-big-play-centered vjs-fluid">
            <!-- <source :src="currentRow.recordVideoUrl" type="application/x-mpegURL"> -->
             <p class="vjs-no-js">
              To view this video please enable JavaScript, and consider upgrading to a
              web browser that
              <a href="https://videojs.com/html5-video-support/" target="_blank">
                supports HTML5 video
              </a>
            </p>
          </video>
      </el-dialog>
      <el-dialog  :visible.sync="playNumSetDialogShowed" title="设置直播间虚拟播放次数" width="400px">
         <el-form :disabled="isSubmiting" :model="formData" :rules="joinNumFormRules" label-width="120px">
           <el-form-item label="实际播放次数">
             {{formData.viewNum}}
           </el-form-item>
           <el-form-item label="虚拟播放次数" prop="viewNumVirtual">
             <el-input-number v-model="formData.viewNumVirtual" placeholder="请设置虚拟访问次数"></el-input-number>
           </el-form-item>
         </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="playNumSetDialogShowed = false">取消</el-button>
              <el-button :loading="isSubmiting" type="primary" @click="submitFormAction">确定</el-button>
          </div>
      </el-dialog>
    </div>
  </template>
  <script>
  import { validatenull } from "@/util/validate";
  // import { DIC } from "@/const/dic";
  import {  getLabelFromDicV2 } from "@/const/dic";
  import { nowDate } from "../../util/date";
  import * as apiObj from "../../api/videoChannel";
  import { videoChannelRecordTableOption} from "@/const/videoChannel/videoChannelRecordTableOption.js";

  import  videojs from  'video.js/dist/video.min'
  import 'video.js/dist/video-js.min.css'
  // import 'videojs-flash/dist/videojs-flash';

  
  export default {
    props:{
       isSelect:{
         type:Boolean,
         default: false
       }
    },
    data() {
      return {
        joinNumFormRules:{
          viewNumVirtual:[{
            required:true,
            message:'请输入虚拟播放次数',
            trigger:'change'
          }]
        },
        formData:{
          viewNumVirtual:0,
          viewNum:0
        },
        isSubmiting:false,
        videoPriviewDialogShowed:false,
        playNumSetDialogShowed:false,
        bachDeleting: false,
        currentRow:null,
        tableOption: {}, //表格设置属性
        tableData: [], //表格的数据
        downloadLoading:false,
        tableLoading: false,
        tableQueryParam: {},
        page: {
          total: 0, //总页数
          currentPage: 1, //当前页数
          pageSize: 10 //每页显示多少条
        }
      };
    },
    created() {
      //初始化数据格式
      this.tableOption = {...videoChannelRecordTableOption};
      if(this.isSelect) {
        this.tableOption.menu = true;
        this.tableOption.index = false;
        this.tableOption.selection = false;
      }
      this.handleList();
    },
    methods: {
       handleShowSetPlayView(row){
         this.formData = row;
         this.playNumSetDialogShowed = true;
      },
      handleCurrentChange(page) {
        this.page.currentPage = page;
        this.handleList();
      },
      handleSizeChange(size) {
        this.page.pageSize = size;
        this.handleList();
      },
      hanldePlay(row){
        this.videoPriviewDialogShowed = true;
        this.$nextTick(()=>{
            if(this.playerObj){
              const data = {
                src: location.protocol=='https:'? row.recordVideoUrl.replace('http://','https://'):row.recordVideoUrl
              };
              this.playerObj.pause();
              this.playerObj.src(data);
              this.playerObj.load(data);
              this.playerObj.posterImage.setSrc(row.coverImg);
              return;
            }
            this.playerObj = videojs(this.$refs.myVideo, {
              controls: true, // 是否显示控制条
              poster: row.coverImg, // 视频封面图地址
              preload: 'auto',
              autoplay: false,
              fluid: true, // 自适应宽高
              language: 'zh-CN', // 设置语言
              muted: false, // 是否静音
              inactivityTimeout: false,
              controlBar: { // 设置控制条组件
                /* 设置控制条里面组件的相关属性及显示与否
                'currentTimeDisplay':true,
                'timeDivider':true,
                'durationDisplay':true,
                'remainingTimeDisplay':false,
                volumePanel: {
                  inline: false,
                }
                */
                /* 使用children的形式可以控制每一个控件的位置，以及显示与否 */
                children: [
                  {name: 'playToggle'}, // 播放按钮
                  {name: 'currentTimeDisplay'}, // 当前已播放时间
                  {name: 'progressControl'}, // 播放进度条
                  {name: 'durationDisplay'}, // 总时间
                  { // 倍数播放
                    name: 'playbackRateMenuButton',
                    'playbackRates': [0.5, 1, 1.5, 2, 2.5]
                  },
                  {
                    name: 'volumePanel', // 音量控制
                    inline: false, // 不使用水平方式
                  },
                  {name: 'FullscreenToggle'} // 全屏
                ]
              },
              sources:[ // 视频源
                  {
                      src: location.protocol=='https:'? row.recordVideoUrl.replace('http://','https://'):row.recordVideoUrl
                      // type: 'video/mp4',
                      // poster: '//vjs.zencdn.net/v/oceans.png'
                  }
              ]
            }, function (){
              console.log('视频可以播放了',this);
            });
        });
      },
      // 开启或者关闭直播间录制功能
      handleSetTopFlag(row,flag){
        const msg = flag == 1 ? '确认置顶吗?':'确认取消置顶吗?';
        this.showConfirm(msg,()=>{
            let p;
            if(flag) {
              p=apiObj.setRecordTop(row.id);
            } else {
              p=apiObj.cancelRecordTop(row.id);
            }
            p.then(()=>{
              this.success();
              this.handleList();
            });
        });
      },
      handleSelectDataItem(row){
        this.$emit('onSelectVideoChannel',row);
      },
      handleSelectionChange(args) {
        this.currentSelectedRowIds = args.map(el => el.id);
      },
      hasChanged(params1,params2){
        return Object.keys(params1).some(key=>params2[key] != params1[key]);
    },
    handleSearchChange(params) {
      if(this.hasChanged(params,this.tableQueryParam)){
        this.page.currentPage = 1;
      }
        this.tableQueryParam = params;
        this.handleList();
      },
      
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done, reject) {
        apiObj.update(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },      
      handleDel(row, index) {
        this.$confirm('是否确认删除', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            apiObj.deleteRecord(
              row.id
            ).then(() => {
              this.handleList();
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
            });
          })
          .catch(() => {});
      },    
      handleRefreshChange() {
        this.handleList();
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        this.tableLoading = true;
        apiObj.recordList({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam
        })
          .then(data => {
            this.tableData = data.data || data.dataList || [];
            this.page.total = data.total;
            this.tableLoading = false;
          })
          .catch(() => {
            this.tableLoading = false;
          });
      },     
      handleCloseDialog(){
        if(this.playerObj){
          this.playerObj.pause();
        }
      },
      submitFormAction(){
          this.isSubmiting = true;
          apiObj.setViewNum(this.formData.id,this.formData.viewNumVirtual).then(()=>{
            this.playNumSetDialogShowed = false;
            this.success();
          }).finally(()=>{
            this.isSubmiting = false;
          });
      },
      handleExport() {
        this.downloadLoading = true;
        apiObj.recordList({
          pageNo: 1,
          pageSize: 3000,
          ...this.tableQueryParam
        }).then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const columns = this.tableOption.column.filter(el=>el.hide !== true && el.type!='upload');
            const tHeader = columns.map(el=>el.label);
            const filterVal = columns.map(el=>el.prop);
            const data = this.formatJson(filterVal, res.data || res.dataList);

            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: "直播录制" + nowDate()
            });
            this.downloadLoading = false;
          });
        });
      },
      formatJson(filterVal, jsonData) {      
        return jsonData.map(v =>
          filterVal.map(j => {
            return getLabelFromDicV2(this.$refs.crud.DIC,j,v[j]);
          })
        );
      }
    }
  };
  </script>
<style scoped>
#my-video{
  margin: 0 auto;
  display: block;
}
</style>
